﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Kz.Telegram.Bot.Infrastructure.Helpers
{
    public static class IpHelper
    {
        public static string GetLocalIPv4Address()
        {
            IPAddress localIP = null;
            //获取本机所有的IP地址列表
            IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress item in addressList)
            {
                //判断是否是IPv4地址
                if (item.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = item;
                    break;
                }
                else
                    continue;
            }
            return localIP == null ? "" : localIP.ToString();
        }

        /// <summary>
        /// 获取客户端Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientIP(this HttpContext context)
        {
            try
            {
                var ip = context.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();
                if (!string.IsNullOrEmpty(ip))
                    return ip.IpReplace();

                ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                if (!string.IsNullOrEmpty(ip))
                    return ip.IpReplace();

                ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();

                return ip.IpReplace();
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inip"></param>
        /// <returns></returns>
        private static string IpReplace(this string ip)
        {
            if (ip.Contains("::ffff:"))
            {
                ip = ip.Replace("::ffff:", "");
            }
            return ip;
        }
    }
}
